package com.app.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.app.mapper.FwRenewalRecordMapper;
import com.app.mapper.UserMapper;
import com.app.model.FwRenewalRecord;
import com.app.model.TenantRelationship;
import com.app.model.User;
import com.app.service.IFwRenewalRecordService;
import com.app.service.ITenantRelationshipService;
import com.app.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.app.util.PdfToImageUtil.convertPdfToImages;
import static com.app.util.RenewalContractGenerator.generatePdf;

/**
 * <p>
 * 房屋续租记录 前端控制器
 * </p>
 *
 * @author yoominic
 * @since 2025-03-21
 */
@Api(tags = "房屋续租记录")
@RestController
@RequestMapping("/fwRenewalRecord")
public class FwRenewalRecordController {

    @Autowired
    private IFwRenewalRecordService fwRenewalRecordService;

    @Autowired
    private ITenantRelationshipService tenantRelationshipService;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FwRenewalRecordMapper fwRenewalRecordMapper;

    @ApiOperation(value = "小程序---申请续租", notes = "小程序---申请续租")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fwRenewalRecordDTO", value = "房屋续租记录DTO", required = true, dataType = "FwRenewalRecordDTO")
    })
    @PostMapping("applet/applyForFwRenewalRecord")
    public Result applyForFwRenewalRecord(HttpServletRequest request, @RequestBody FwRenewalRecord fwRenewalRecordDTO) {

        String token = request.getHeader("token");
        String userId = StpUtil.getLoginIdByToken(token).toString();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userId);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return Result.error("用户不存在");
        }

        //查询房屋的最新的承租人
        QueryWrapper<TenantRelationship> tenantRelationshipQueryWrapper = new QueryWrapper<>();
        tenantRelationshipQueryWrapper.eq("unique_id", fwRenewalRecordDTO.getIdValue());
        tenantRelationshipQueryWrapper.orderByDesc("tenant_serial_number");
        tenantRelationshipQueryWrapper.last("limit 1");
        TenantRelationship tenantRelationship = tenantRelationshipService.getOne(tenantRelationshipQueryWrapper);

        String lease_certificate_number = tenantRelationship.getLeaseCertificateNumber();
        //生成租赁合同编号
        String contractNumber = generateContractNumber(lease_certificate_number);

        if (fwRenewalRecordDTO.getId() == null) {
            fwRenewalRecordDTO.setContractNumber(contractNumber);
            fwRenewalRecordDTO.setStatus(1);
            fwRenewalRecordDTO.setUserId(Integer.parseInt(userId));
            fwRenewalRecordDTO.setCreateTime(LocalDateTime.now());
            fwRenewalRecordDTO.setTenantRelationshipId(tenantRelationship.getId());
            fwRenewalRecordService.save(fwRenewalRecordDTO);
        } else {
            //签订合同
            QueryWrapper<FwRenewalRecord> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("id", fwRenewalRecordDTO.getId());
            FwRenewalRecord fwRenewalRecord = fwRenewalRecordService.getOne(queryWrapper1);
            if (fwRenewalRecord.getContractAddress() == null && fwRenewalRecordDTO.getContractAddress() != null) {
                fwRenewalRecordDTO.setContractSignTime(LocalDateTime.now());
                fwRenewalRecordService.updateById(fwRenewalRecordDTO);
            }
        }

        return Result.success("操作成功！");
    }


    @ApiOperation(value = "小程序---获取续租记录详情", notes = "小程序---获取续租记录详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "每页条数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "idValue", value = "房屋ID", required = true, dataType = "String")
    })
    @GetMapping("applet/queryFwRenewalRecord")
    public Result queryFwRenewalRecord(HttpServletRequest request,
                                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                                       @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                       String idValue) {

        IPage<FwRenewalRecord> recordIPage = new Page<>(page, limit);

        IPage<FwRenewalRecord> pageResult = fwRenewalRecordMapper.queryFwRenewalRecord(recordIPage, idValue);

        JSONObject result = new JSONObject();
        result.put("total", pageResult.getTotal());
        result.put("list", pageResult.getRecords());
        return Result.success(result);
    }

    @ApiOperation(value = "小程序---获取续租记录详情", notes = "小程序---获取续租记录详情")
    @GetMapping("applet/getRenewalRecordById")
    public Result getRenewalRecordById(String idValue) throws Exception {
        QueryWrapper<FwRenewalRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_value", idValue);
        FwRenewalRecord fwRenewalRecord = fwRenewalRecordMapper.selectOne(queryWrapper);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        List<Map<String, Object>> list = new ArrayList<>();

        Map<String, Object> map = createMap(1, "续租申请");
        if (fwRenewalRecord != null) {
            map.put("paymentStartTime", fwRenewalRecord.getPaymentStart() == null ? "" : sdf.format(fwRenewalRecord.getPaymentStart()));
            map.put("paymentEndTime", fwRenewalRecord.getPaymentEnd() == null ? "" : sdf.format(fwRenewalRecord.getPaymentEnd()));
        }

        Map<String, Object> map1 = createMap(2, "房管中心审核");
        map1.put("name", "待房管中⼼审核");
        map1.put("content", "预计需要3个⼯作⽇，请耐⼼等待");
        if (fwRenewalRecord != null) {
            map1.put("createTime", "提交时间：" + (fwRenewalRecord.getCreateTime() == null ? "" : dtf.format(fwRenewalRecord.getCreateTime())));
            if (fwRenewalRecord.getStatus() == 1) {
                map1.put("currentNode", true);
            }
        }

        Map<String, Object> map2 = createMap(3, "签订准备");
        map2.put("name", "待管理员发起线上合同签订");
        map2.put("content", "预计需要1个⼯作⽇，请耐⼼等待");
        if (fwRenewalRecord != null) {
            map2.put("createTime", "审核通过时间：" + (fwRenewalRecord.getReviewTime() == null ? "" : dtf.format(fwRenewalRecord.getReviewTime())));
            if (fwRenewalRecord.getStatus() == 2 && fwRenewalRecord.getContractAddress() != null) {
                map2.put("currentNode", true);
                String string = generatePdf(fwRenewalRecord.getContractNumber() + "续租合同");
                fwRenewalRecord.setContractAddress(string);
                fwRenewalRecordMapper.updateById(fwRenewalRecord);
                map2.put("fileUrl", fwRenewalRecord.getContractAddress());
            }
        }

        Map<String, Object> map3 = createMap(4, "签订合同");
        if (fwRenewalRecord != null) {
            map3.put("fileUrl", fwRenewalRecord.getContractAddress());
            if (fwRenewalRecord.getStatus() == 2 && fwRenewalRecord.getContractSignTime() != null) {
                map3.put("currentNode", true);
            }
        }
        if (fwRenewalRecord != null && StrUtil.isNotBlank(fwRenewalRecord.getContractAddress())) {
            String filePath = System.getProperty("user.dir") + File.separator + "file" + File.separator;
            List<File> jpg = convertPdfToImages(new File(fwRenewalRecord.getContractAddress()), filePath, "jpg", 200);
            fwRenewalRecord.setContractPicture(jpg);
        }

        Map<String, Object> map4 = createMap(5, "续租成功");
        map4.put("name", "续签成功");
        if (fwRenewalRecord != null) {
            if (fwRenewalRecord.getStatus() == 2 && fwRenewalRecord.getContractAddress() != null) {
                map4.put("currentNode", true);
            }
        }

        list.add(map);
        list.add(map1);
        list.add(map2);
        list.add(map3);
        list.add(map4);
        if (fwRenewalRecord == null) {
            fwRenewalRecord = new FwRenewalRecord();
            fwRenewalRecord.setCurrentNodeList(list);
        } else {
            fwRenewalRecord.setCurrentNodeList(list);
        }
        return Result.success(fwRenewalRecord);
    }

    private Map<String, Object> createMap(int id, String title) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("title", title);
        map.put("currentNode", false);
        return map;
    }


    @ApiOperation(value = "管理后台---获取续租记录列表", notes = "管理后台---获取续租记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "每页条数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "status", value = "租赁合同状态( 1待审核、2生效中、3已终止、4争议处理中)", required = false, dataType = "String"),
            @ApiImplicitParam(name = "houseType", value = "房屋类型", required = false, dataType = "String"),
            @ApiImplicitParam(name = "fwkeyword", value = "房屋关键词（租赁证编号、地址）", required = false, dataType = "String"),
            @ApiImplicitParam(name = "yhkeyword", value = "承租人关键词（姓名、身份证号、手机号）", required = false, dataType = "String"),
            @ApiImplicitParam(name = "contractNumber", value = "租赁合同编号关键词", required = false, dataType = "String")
    })
    @GetMapping("admin/getFwRenewalRecordList")
    public Result adminGetFwRenewalRecordList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                              @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                              String status, String houseType, String fwkeyword, String yhkeyword, String contractNumber) {

        Page<FwRenewalRecord> pageParam = new Page<>(page, limit);

        IPage<FwRenewalRecord> pageResult = fwRenewalRecordMapper.adminGetFwRenewalRecordList(pageParam, status, houseType, fwkeyword, yhkeyword, contractNumber);

        JSONObject result = new JSONObject();
        result.put("total", pageResult.getTotal());
        result.put("items", pageResult.getRecords());
        return Result.success(result);
    }


    @ApiOperation(value = "管理后台---获取续租记录详情", notes = "管理后台---获取续租记录详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "续租记录ID", required = true, dataType = "Integer")
    })
    @GetMapping("admin/getFwRenewalRecordById")
    public Result adminGetFwRenewalRecordById(Integer id) {
        FwRenewalRecord fwRenewalRecord = fwRenewalRecordMapper.adminGetFwRenewalRecordById(id);
        if (fwRenewalRecord == null) {
            return Result.error("续租记录不存在！");
        }
        return Result.success(fwRenewalRecord);
    }


    @ApiOperation(value = "管理后台---审核续租记录", notes = "管理后台---审核续租记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fwRenewalRecord", value = "续租记录", required = true, dataType = "FwRenewalRecord")
    })
    @PostMapping("admin/examineFwRenewalRecord")
    public Result examineFwRenewalRecord(HttpServletRequest request, @RequestBody FwRenewalRecord fwRenewalRecord) {

        String token = request.getHeader("token");
        String userId = StpUtil.getLoginIdByToken(token).toString();

        QueryWrapper<FwRenewalRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", fwRenewalRecord.getId());
        FwRenewalRecord record = fwRenewalRecordMapper.selectOne(queryWrapper);
        if (record == null) {
            return Result.error("续租记录不存在！");
        }
        if (record.getStatus() != 1) {
            return Result.error("续租记录状态不正确！");
        }
        if (fwRenewalRecord.getStatus() == 5) {
            fwRenewalRecord.setRemarks(fwRenewalRecord.getRemarks());
        }
        fwRenewalRecord.setStatus(fwRenewalRecord.getStatus());
        fwRenewalRecord.setAuditorSysUserId(Integer.parseInt(userId));
        fwRenewalRecord.setReviewTime(LocalDateTime.now());
        fwRenewalRecordMapper.updateById(fwRenewalRecord);
        return Result.success("操作成功！");
    }


    @ApiOperation(value = "管理后台---发起续租", notes = "管理后台---发起续租")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fwRenewalRecord", value = "续租记录", required = true, dataType = "FwRenewalRecord")
    })
    @PostMapping("admin/forFwRenewalRecord")
    public Result adminForFwRenewalRecord(HttpServletRequest request, @RequestBody FwRenewalRecord fwRenewalRecordDTO) {
        String token = request.getHeader("token");
        String userId = StpUtil.getLoginIdByToken(token).toString();

        //查询房屋的最新的承租人
        QueryWrapper<TenantRelationship> tenantRelationshipQueryWrapper = new QueryWrapper<>();
        tenantRelationshipQueryWrapper.eq("unique_id", fwRenewalRecordDTO.getIdValue());
        tenantRelationshipQueryWrapper.orderByDesc("tenant_serial_number");
        tenantRelationshipQueryWrapper.last("limit 1");
        TenantRelationship tenantRelationship = tenantRelationshipService.getOne(tenantRelationshipQueryWrapper);

        String lease_certificate_number = tenantRelationship.getLeaseCertificateNumber();
        //生成租赁合同编号
        String contractNumber = generateContractNumber(lease_certificate_number);

        if (fwRenewalRecordDTO.getId() == null) {
            fwRenewalRecordDTO.setContractNumber(contractNumber);
            fwRenewalRecordDTO.setStatus(1);
            fwRenewalRecordDTO.setUserId(Integer.parseInt(userId));
            fwRenewalRecordDTO.setCreateTime(LocalDateTime.now());
            fwRenewalRecordDTO.setTenantRelationshipId(tenantRelationship.getId());
            fwRenewalRecordService.save(fwRenewalRecordDTO);
        } else {
            //签订合同
            QueryWrapper<FwRenewalRecord> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("id", fwRenewalRecordDTO.getId());
            FwRenewalRecord fwRenewalRecord = fwRenewalRecordService.getOne(queryWrapper1);
            if (fwRenewalRecord.getContractAddress() == null && fwRenewalRecordDTO.getContractAddress() != null) {
                fwRenewalRecordDTO.setContractSignTime(LocalDateTime.now());
                fwRenewalRecordService.updateById(fwRenewalRecordDTO);
            }
        }

        return Result.success("操作成功！");
    }


    @ApiOperation(value = "管理后台---删除续租记录", notes = "管理后台---删除续租记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "续租记录ID", required = true, dataType = "Integer")
    })
    @GetMapping("admin/deleteFwRenewalRecord")
    public Result deleteFwRenewalRecord(Integer id) {
        fwRenewalRecordService.removeById(id);
        return Result.success("操作成功！");
    }


    @ApiOperation(value = "小程序---获取登录用户的续租记录列表", notes = "小程序---获取登录用户的续租记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "每页条数", required = false, dataType = "Integer")
    })
    @GetMapping("applet/getLoginUserFwRenewalRecordList")
    public Result appletGetLoginUserFwRenewalRecordList(HttpServletRequest request,
                                                        @RequestParam(value = "page") Integer page,
                                                        @RequestParam(value = "limit") Integer limit) {

        String token = request.getHeader("token");
        String userId = StpUtil.getLoginIdByToken(token).toString();

        Page<FwRenewalRecord> pageParam = new Page<>(page, limit);

        IPage<FwRenewalRecord> pageResult = fwRenewalRecordMapper.getLoginUserFwRenewalRecordList(pageParam, Integer.valueOf(userId));

        JSONObject result = new JSONObject();
        result.put("total", pageResult.getTotal());
        result.put("items", pageResult.getRecords());
        return Result.success(result);
    }


    public static String generateContractNumber(String lease_certificate_number) {
        // 获取当前日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String datePart = dateFormat.format(new Date());

        // 生成随机数部分，这里生成 4 位随机数
        Random random = new Random();
        int randomNum = random.nextInt(9000) + 1000;
        String randomPart = String.valueOf(randomNum);

        // 组合成合同编号，这里假设合同编号以 "RENT-" 开头
        return "RENT-" + datePart + "-" + lease_certificate_number + "-" + randomPart;
    }

    public static void main(String[] args) {
        String lease_certificate_number = "L3823";
        String contractNumber = generateContractNumber(lease_certificate_number);
        System.out.println("生成的租赁合同编号: " + contractNumber);
    }


}

